import logging
import datetime
import copy
import utility
import config
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from google.appengine.api import memcache

class ResultView(webapp.RequestHandler):
    def get(self):      
        query = self.request.get('q', '')
        rsgroupid = self.request.get('gid', '')
        rsgrouppage = int(self.request.get('page', '1'))

        payload = {}
        newfilters = []
        newgroupview = {}
        count = 0
        groups = []       
        groupid = 0
        analysisid = 1

        # get the clustered search result data            
        results = memcache.get(query+'_web')
        results2 = memcache.get(query+'_cluster')
        if results2 is None or results is None:
            results = utility.get_N_google_search_results(query, 300)
            if len(results) == 0:
                logging.debug('error.html')
                error = template.render('error.html', {})
                self.response.out.write(error)
                return
            try:
                seal = utility.seal_query_xml(query, results)
                results2 = utility.get_cluster_results(c2stream=seal)
                memcache.add_multi({'_web':results,
                                    '_cluster':results2},
                                   key_prefix=query, time=config.MEMCACHETIME)
            except:
                logging.debug('error.html')
                error = template.render('error.html', {})
                self.response.out.write(error)
                return
            logging.debug('Use From Web!--' + query)
        else:
            logging.debug('Use Cache!--' + query)

        count = len(results)

        for resu in results2['clusters']:
            title =''
            for des in resu['phrases']:#resu['description']:
                title += des
                group = {'size': len(resu['documents']), 'list': [], 
                         'description': title, 'page': [], 'more': False}
                if group["size"] > config.DMORE:
                    group["more"] = True
                newfilters.append(group)

            groupid += 1
            for item in resu['documents']:
                index = int(item) - 1
                summary =  results[index]['Summary']
                if len(summary) == 0:
                    summary = "##"
                siteinfo = {'id': index + 1, 'title': results[index]['Title'][:50], 'summary':summary,
                            'url': results[index]['Url'][:30], 'clickurl': results[index]['ClickUrl'][:500], 
                            'image': 'http://' + config.ANALYSISSERVERNAME + str(analysisid) + '.appspot.com/?url=' + results[index]['ClickUrl']}
                analysisid = analysisid % config.ANALYSISSERVERS + 1
                newfilters[len(newfilters)-1]["list"].append(siteinfo)

        
        if int(rsgroupid) > len(newfilters):
            logging.debug('error.html')
            error = template.render('error.html', {})
            self.response.out.write(error)
            return

        groupmore = False
        if str(len(newfilters)) > config.GMORE:
            groupmore = True
        newgroupview = newfilters[int(rsgroupid) - 1]
        newgroupview['list'] = newgroupview['list'][(rsgrouppage-1)*config.RESULTPAGE:(rsgrouppage)*config.RESULTPAGE]

        pagesf = newgroupview['size']/(config.RESULTPAGE*1.0)
        pages = int(pagesf)
        if pagesf > pages:
            pages += 1

        for i in range(pages):
            newgroupview['page'].append(i + 1)

        pagenext = rsgrouppage + 1
        if pagenext > pages:
            pagenext = 0
        pagepre = rsgrouppage - 1

        payload = dict( filters=newfilters, query=query, rsgroupid=rsgroupid, rsgrouppage=rsgrouppage, 
                        pagenext=pagenext, pagepre=pagepre, groupmore=groupmore, size=str(count), 
                        filtersize=str(len(newfilters)), groupview=newgroupview)
        resp = template.render('group.html', payload)
        self.response.out.write(resp)

